<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\controller\My;
use app\admin\model\Admin;
use think\Db;
use app\admin\model\caiwu\Money as moneylog;
use think\Cache;
use app\common\controller\MyHelp;

/**
 * 开放平台
 */
class Openapi extends Api
{
    protected $noNeedLogin = "*";
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 签名验证
     */
    protected function checkSign()
    {

        $param = $this->request->request();

        $mobile = $this->request->request('mobile');
        $sign = $this->request->request('sign');
        $timestamp = $this->request->request('timestamp');
        //return json($this->request->request());
        if (!$timestamp || !$sign || !$mobile) {
            return $this->error('公共参数缺失,请检查mobile,sign,timestamp');
        }
        $nowTime = time();
        if ($nowTime - $timestamp > 600) {
            return $this->error('签名过期');
        }

        $r = Admin::getByUsername($mobile);
        if (!$r) {
            return $this->error('token错误');
        }
        $token = $r['api_token'];
        unset($param['s']);
        $getSign = $this->getSign($param, $token);
        // dump($param);
        // echo  $sign;
        if ($getSign != $sign) {
            return $this->error('签名错误');
        }
        return $r;
    }
    /**
     * 获取签名
     */
    protected function getSign($param, $key)
    {
        $signPars = "";
        ksort($param);
        foreach ($param as $k => $v) {
            if ("sign" != $k && "" != htmlspecialchars_decode($v)) {
                $signPars .= $k . htmlspecialchars_decode($v);
            }
        }
        $signPars = $key . $signPars;
        //echo  $signPars;

        $sign = md5($signPars);
        //echo $signPars."<br>".$sign."<br>";
        return $sign;
    }
    /**
     * ua换取品牌
     */
    public function uaToBrand()
    {
        $admin = $this->checkSign();
        $ua = $this->request->request('ua');
        // $admin = [
        //     'id' => 1,
        //     'money' => 100
        // ];
        $rst = my::getPhonetype($ua);
        return $this->success('', $rst);
    }
    public function getBalance()
    {
        $admin = $this->checkSign();
        // $admin = [
        //     'id' => 1,
        //     'money' => 100
        // ];
        return $this->success('ok', $admin['money']);
    }
    /**
     * 话费提交订单
     */
    public  function subOrderHf()
    {
        $admin = $this->checkSign();
        // $admin = [
        //     'id' => 1,
        //     'money' => 100
        // ];
        $id = $this->request->request('id');
        $mobile = $this->request->request('mobile');

        $notifyUrl = $this->request->request('notifyUrl');
        $mobile = str_replace(' ', '', $mobile);
        if (strlen($mobile) != 11) {
            return $this->error('手机号格式有误');
        }


        if (cache::get('subOrderHf' . $mobile)) {
            $this->error('请勿频繁提交');
        }
        cache::set('subOrderHf' . $mobile, 2, 2);

        $goods = Db::table('fa_hf_goods')->where('id', $id)->find();
        if (!$goods) {
            $this->error('商品有误');
        }
        if ($goods['statuss'] == '2') {
            return $this->error('禁售状态，无法下单');
        }

        $admin_id = $admin['id'];

        $sxf = 0; //微信手续费


        $zzzz =  MyHelp::getPriceNew($admin, $goods['id']);

        $lr = $zzzz['lr']; //实际用户价格
        $price = $zzzz['price']; //实际用户价格


        // $price = round($goods['price'] - $goods['mz'] / 100, 2); //实际用户价格
        $zzlr = 0; //面值的0.5%
        $lirun = 0; //平台利润


        $Babaohui = new Babaohui();
        $mobileInfo = $Babaohui->getYys1($mobile);
        $mobileInfo_arr = json_decode($mobileInfo, true);
        if (!isset($mobileInfo_arr['result']['Province'])) {
            return $this->error('系统异常或手机号有误');
        }
        $Province = $mobileInfo_arr['result']['Province'];
        $City = $mobileInfo_arr['result']['City'];
        $Isp = $mobileInfo_arr['result']['Isp'];
        if ($Isp == '中国移动') {
            $yys = '1';
            $image = 'https://cdn.8nit.cn/uploads/20240101/eb0722ebcea3427f48c4dd8fada552a1.png';
        } elseif ($Isp == '中国联通') {
            $yys = '2';
            $image = 'https://cdn.8nit.cn/uploads/20240101/a09d4985e64f735f69f51dfe7e13d1be.png';
        } elseif ($Isp == '中国电信') {
            $yys = '3';
            $image = 'https://cdn.8nit.cn/uploads/20240101/fce2efbd9e7765b73cd9aed2cb6ea839.png';
        } else {
            $this->error('不支持的运营商');
        }
        $orderno = 'HF' . date("Ymdhis")  . mt_rand(1000000, 99999999);
        $admin = db::table('fa_admin')->where('id', $admin_id)->find();
        $money = $admin['money'];
        if ($money < $price) {
            return $this->error('余额不足');
        }

        $data = [
            'admin_id' => $admin_id,
            'orderno' => $orderno,
            'account' => $mobile,
            'createtime' => time(),
            'update_time' => time(),
            'goodsid' => $id,
            'code' => $goods['code'],
            'mz' => $goods['mz'],
            'user_id' => 0,
            'province' => $Province,
            'city' => $City,
            'yys' => $yys,
            'cztype' => $goods['type'],
            'lirun' => $lirun,
            'price' => $price,
            'cbprice' => $goods['cb'],
            'sxf' => $sxf,
            'zzlr' => $zzlr,
            'from' => '3',
            'image' => $image,
            'title' => $goods['title'],
            'ordernoO' => $orderno,
            'notifyUrl' => $notifyUrl,
            'lr_arr' => json_encode($lr),
            'api' => $goods['api']
        ];
        Db::table('fa_hf_order')->insert($data);
        $new_money = round($money - $price, 2);
        Moneylog::create(['admin_id' => $admin_id, 'type' => '2', 'money' => $price * -1, 'before' => $money, 'after' => $new_money, 'memo' => 'API下单', 'type1' => 1, 'orderPc' => $orderno]);

        db::table('fa_admin')->where('id', $admin_id)->update(['money' => $new_money]);

        $Babaohui = new Babaohui();
        $rst =  $Babaohui->addOrderHF1($orderno, $mobile, $goods['code'], $goods['type'], $goods['api']);

        if ($rst['code'] == 1) {
            Db::table('fa_hf_order')->where('orderno', $orderno)->update(['statuss' => '2', 'remark' => '充值中', 'api_order' => $rst['order']]);
            return $this->success('提交成功', ['orderno' => $orderno]);
        } else {
            Db::table('fa_hf_order')->where('orderno', $orderno)->update(['statuss' => '4', 'remark' => '失败退款:' . $rst['msg'], 'ccccc' => 100]);
            $before = $new_money;
            $new_money = $admin['money'];
            Moneylog::create(['admin_id' => $admin_id, 'type' => '2', 'money' => $price, 'before' => $before, 'after' => $new_money, 'memo' => 'API下单退款', 'type1' => 2, 'orderPc' => $orderno]);

            db::table('fa_admin')->where('id', $admin_id)->update(['money' => $new_money]);
            return $this->error('提交失败：' . $rst['msg']);
        }
    }
}
